package com.clement.spring.study.config;

import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.format.datetime.DateFormatter;
import org.springframework.format.datetime.DateFormatterRegistrar;
import org.springframework.format.datetime.joda.JodaTimeFormatterRegistrar;
import org.springframework.format.number.NumberFormatAnnotationFormatterFactory;
import org.springframework.format.support.DefaultFormattingConversionService;
import org.springframework.format.support.FormattingConversionService;

/**
 *Joda Time provides separate distinct types to represent date, time and date-time values.
 * The dateFormatter, timeFormatter and dateTimeFormatter properties of the JodaTimeFormatterRegistrar
 * should be used to configure the different formats for each type.
 * The DateTimeFormatterFactoryBean provides a convenient way to create formatters.
 */
@Configuration
public class TimeFormatConfiguration {
    @Bean
    @Primary
    public FormattingConversionService conversionService() {
        //Use the DefaultFormattingConversionService but do not register defaults
        DefaultFormattingConversionService defaultFormattingConversionService = new DefaultFormattingConversionService(false);
        // Ensure @NumberFormat is still supported
        defaultFormattingConversionService.addFormatterForFieldAnnotation(new NumberFormatAnnotationFormatterFactory());
        //Register date conversion with a specific global format
        JodaTimeFormatterRegistrar registrar = new JodaTimeFormatterRegistrar();
        registrar.setDateFormatter(DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"));
        registrar.registerFormatters(defaultFormattingConversionService);
        return defaultFormattingConversionService;
    }
}
